import 'dart:convert';
import 'dart:io';
import 'package:latlong2/latlong.dart';

///高德API

final HttpClient _client = HttpClient();
const _key = "8b5518816fc4b0948d3695931a5ab047";

Future<dynamic> sendAPIRequest(String uri) async {
  try {
    var request = await _client.openUrl("GET", Uri.parse(uri));
    request.headers.add("accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");

    request.headers.add(
        "accept-language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
    request.headers.add("user-agent",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");

    var response = await request.close();
    var data = utf8.decode((await response.first));
    return json.decode(data);
  } catch(err) {
    print(err);
    return null;
  }
}

///根据经纬度查询详细地址
/*

{status: 1, regeocode: {addressComponent: {city: [], province: 北京市, adcode: 110102, district: 西城区, towncode: 1101020 streetNumber: {number: 2号, location: 116.389834,39.905294, direction: 西, distance: 129.285, street: 西长安街}, country:ownship: 西长安街街道, businessAreas: [{location: 116.391134,39.895089, name: 大栅栏, id: 110102}, {location: 116.375880,3 name: 宣武门, id: 110102}], building: {name: [], type: []}, neighborhood: {name: [], type: []}, citycode: 010}, formatteddress: 北京市西城区西长安街街道人大会堂西路国家大剧院}, info: OK, infocode: 10000}

 */
Future<dynamic> getAddressByLatlng(LatLng latlng) async {
  const String uri = "https://restapi.amap.com/v3/geocode/regeo?key=${_key}";

  String params = "${latlng.longitude.toStringAsFixed(6)},${latlng.latitude.toStringAsFixed(6)}";
  
  return sendAPIRequest(uri + "&location=${params}");
}

///根据经纬度获取天气
/*

{status: 1, count: 1, info: OK, infocode: 10000, forecasts: [{city: 西城区, adcode: 110102, province: 北京, reporttime: 20-15 21:02:33, casts: [{date: 2025-05-15, week: 4, dayweather: 晴, nightweather: 晴, daytemp: 29, nighttemp: 15, daywind: 西 nightwind: 西南, daypower: 1-3, nightpower: 1-3, daytemp_float: 29.0, nighttemp_float: 15.0}, {date: 2025-05-16, week: 5,ayweather: 雷阵雨, nightweather: 雷阵雨, daytemp: 29, nighttemp: 14, daywind: 南, nightwind: 南, daypower: 1-3, nightpoweraytemp_float: 29.0, nighttemp_float: 14.0}, {date: 2025-05-17, week: 6, dayweather: 多云, nightweather: 多云, daytemp: 23,httemp: 12, daywind: 西北, nightwind: 西北, daypower: 1-3, nightpower: 1-3, daytemp_float: 23.0, nighttemp_float: 12.0}, {: 2025-05-18, week: 7, dayweather: 雷阵雨, nightweather: 多云, daytemp: 25, nighttemp: 15, daywind: 西南, nightwind: 西南,: 1-3, nightpower: 1-3, daytemp_float: 25.0, nighttemp_float: 15.0}]}]}

 */
Future<dynamic> getWeather(LatLng latlng) async {
  var address = await getAddressByLatlng(latlng);
  if(address == null) {
    return null;
  }

  int? code = int.tryParse(address['regeocode']['addressComponent']['adcode'].toString());
  if(code == null) {
    return null;
  }

  String uri = "https://restapi.amap.com/v3/weather/weatherInfo?key=${_key}&city=${code}&extensions=all";
  return sendAPIRequest(uri);
}

///根据模糊地址搜索详细信息
/*
{status: 1, info: OK, infocode: 10000, count: 1, geocodes: [{formatted_address: 湖北省黄石市黄石港区湖北师范大学图书馆, co: 湖北省, citycode: 0714, city: 黄石市, district: 黄石港区, township: [], neighborhood: {name: [], type: []}, building: {nype: []}, adcode: 420202, street: [], number: [], location: 115.065412,30.230712, level: 兴趣点}]}

 */
Future<dynamic> searchDetailAddress(String key,String? city) {
  String uri = "https://restapi.amap.com/v3/geocode/geo?key=${_key}&address=${key}";
  if(city != null) {
    uri+="&city=$city!";
  }

  return sendAPIRequest(uri);
}

